package com.wkhyapp.lm.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.Log;
import com.wkhyapp.lm.MainActivity;
import com.wkhyapp.lm.constant.Constant;
import com.wkhyapp.lm.constant.MessageEvent;
import com.wkhyapp.lm.http.ApiStores;
import com.wkhyapp.lm.http.AppClient;
import com.wkhyapp.lm.http.net.LoginRequest;
import com.wkhyapp.lm.http.net.LoginRespone;
import com.wkhyapp.lm.http.net.SuperResponse;
import com.wkhyapp.lm.http.vo.Member;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.utils.PreferenceUtils;
import com.wkhyapp.lm.view.LoginActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.subscriptions.CompositeSubscription;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    private IWXAPI api = null;
    protected ApiStores apiStores;
    private CompositeSubscription mCompositeSubscription;
    public WXEntryActivity() {
        super();
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID,true);
        api.registerApp(Constant.APP_ID);
        api.handleIntent(getIntent(), this);

        apiStores = AppClient.retrofit().create(ApiStores.class);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        MProgressDialog.showProgress(this,"正在请求....");
    }


    @Subscribe
    public void onEvent(MessageEvent event){
        android.util.Log.d("onEventBus",event.toString());
    }

    @Override
    public void onResp(BaseResp resp) {
        MProgressDialog.dismissProgress();
        Log.d("WXTest", JSON.toJSONString(resp));
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
             Log.i("WXTest","onResp OK");
             if(resp instanceof SendAuth.Resp){
                    SendAuth.Resp newResp = (SendAuth.Resp) resp;
                    String code = newResp.code;
                 if("wechat_author".equals(newResp.state)){
                     author(code);
                 }else if("wechat_login_author".equals(newResp.state)){
                     author(code);
                 }
                 else if("wechat_login".equals(newResp.state)){
                     login(code);
                 }else {
                     Log.i("WXTest","分享成功");
                 }

               }
              break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Log.i("WXTest","onResp ERR_USER_CANCEL ");
               //   EventBus.getDefault().post(new MessageEvent("wechat_author_cancel","微信录授权取消"));

                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.i("WXTest","onResp ERR_AUTH_DENIED");
                //发送被拒绝
                break;
            default:
                Log.i("WXTest","onResp default errCode " + resp.errCode);
                //发送返回
                break;
        }
        finish();
    }


    public void login(String code) {
        Log.i("WXTest"," 开始登陆");
        MProgressDialog.showProgress(this,"开始登陆....");
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setChannelName(Constant.channelName);
        loginRequest.setWeixinCode(code);
        Log.d("WXTest", JSON.toJSONString(loginRequest));
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(loginRequest));
        final Request request = new Request.Builder()
                .url(ApiStores.API_URL + "/app/login/wxLogin")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("WXTest", "Post String 失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                Log.d("WXTest", String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("WXTest", (responseStr));
                        MProgressDialog.dismissProgress();
                        LoginRespone response = JSON.parseObject(responseStr,LoginRespone.class);
                         MemberUtils.saveMember(response.getItem());
                          PreferenceUtils.getInstance().setPrefInt("userId",response.getItem().getId());
                            Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
                            startActivity(intent);

                            if(LoginActivity.loginActivity!=null){
                                LoginActivity.loginActivity.finish();
                            }
                        }

                });


            }

        });
    }


    /**
     * 授权
     * @param code
     */
    public void author(String code) {
        Log.i("WXTest"," 开始授权111");
//        LoginRequest loginRequest = new LoginRequest();
//        loginRequest.setWeixinCode(code);
//        NetUtils.setParameters(loginRequest);
//        Log.d("WXTest", JSON.toJSONString(loginRequest));
//        OkHttpClient client = new OkHttpClient();
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(loginRequest));
//        final Request request = new Request.Builder()
//                .url(ApiStores.API_URL + "/app/login/binWeiXin")
//                .post(requestBody)
//                .build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.d("WXTest", "Post String 失败");
//            }
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final String responseStr = response.body().string();
//                Log.d("WXTest", String.valueOf(response.code()));
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        EventBus.getDefault().post(new MessageEvent("author_succ","授权成功"));
//                        Log.d("WXTest", (responseStr));
//                        MProgressDialog.dismissProgress();
//                        LXResponse response = JSON.parseObject(responseStr, LXResponse.class);
//                            Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
//                            startActivity(intent);
//                            finish();
//                        }
//
//                });
//            }
//
//        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
